<template>
  <div class="create-post">
    <h2>发布新文章</h2>
    <el-form :model="postForm" label-width="80px" class="post-form" ref="postFormRef">
      <el-form-item label="标题" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
        <el-input v-model="postForm.title" placeholder="文章标题"></el-input>
      </el-form-item>

      <el-form-item label="摘要">
        <el-input
            type="textarea"
            v-model="postForm.summary"
            placeholder="文章摘要（可选）"
            :rows="3"
            maxlength="500"
            show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item label="内容" :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]">
        <el-input
            type="textarea"
            v-model="postForm.content"
            placeholder="文章正文"
            :rows="10"
        ></el-input>
      </el-form-item>

      <el-form-item label="状态">
        <el-radio-group v-model="postForm.status">
          <el-radio :label="1">发布</el-radio>
          <el-radio :label="0">草稿</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitPost">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="default" @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { createPost } from '@/api/posts';

const router = useRouter();
const postFormRef = ref(null);

const postForm = reactive({
  userId: null, // 先空
  title: '',
  summary: '',
  content: '',
  status: 1,
});

// 动态获取当前登录用户id
onMounted(() => {
  const userId = localStorage.getItem('userId');
  if (userId) {
    postForm.userId = Number(userId);
  } else {
    // 如果没登录，可以考虑跳转登录页，或者提示
    ElMessage.warning('请先登录');
    router.push('/login');
  }
});

const submitPost = async () => {
  try {
    if (!postForm.title.trim() || !postForm.content.trim()) {
      ElMessage.warning('标题和内容不能为空');
      return;
    }
    await createPost(postForm);
    ElMessage.success('文章发布成功');
    await router.push('/');
  } catch (error) {
    ElMessage.error(error.response?.data || '发布失败');
  }
};

const resetForm = () => {
  postForm.title = '';
  postForm.summary = '';
  postForm.content = '';
  postForm.status = 1;
};

const goBack = () => {
  router.back();
};
</script>


<style scoped>
.create-post {
  max-width: 720px;
  margin: 40px auto;
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  border-radius: 8px;
}

.post-form {
  margin-top: 20px;
}
</style>
